package com.study.juc2;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author study
 * @version 1.0
 * @date 2020/9/21 16:45
 */
public class NosafeDemo {
    public static void main(String[] args) {

    }

    private static void noSafeHashMap() {
        Map<String, String> map = new ConcurrentHashMap();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                //ConcurrentModificationException
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }

    private static void nosafeSet() {
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                //ConcurrentModificationException
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            }, java.lang.String.valueOf(i)).start();
        }
    }

    private static boolean nosafeList() {
        // List<String> list = new ArrayList<>();
        List<String> list = new CopyOnWriteArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                //ConcurrentModificationException
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }, java.lang.String.valueOf(i)).start();
        }
        try {
            System.out.println("12");
            return true;
        } finally {
            System.out.println("finished");
        }
    }
}
